package main

import (
	proto "com/hr/go-muke/grpc/protobuf/stream"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"io"
	"sync"
	"time"
)

/**
 * @Description
 * @Author huran
 * @Date
 * @Param
 * @return
 **/

func main() {

	conn, err := grpc.DialContext(context.Background(), "localhost:9999", grpc.WithInsecure())
	defer func(conn *grpc.ClientConn) {
		err := conn.Close()
		if err != nil {
			fmt.Println(err)
		}
	}(conn)
	if err != nil {
		panic(err)
	}
	client := proto.NewGreeterClient(conn)
	//stream, err := client.GetStream(context.Background(), &proto.StreamReq{Data: "胡冉"})
	//if err != nil {
	//	if errors.Is(err, io.EOF) {
	//		fmt.Println("服务端发送完毕")
	//		panic(err)
	//	}
	//	panic(err)
	//
	//}
	//for {
	//	recv, err := stream.Recv()
	//	if err != nil {
	//		//服务端返回nil 打印EOF 返回错误就打印错误
	//		fmt.Println("========>>>>", err)
	//		return
	//	}
	//	fmt.Println(recv)
	//}

	//stream, err := client.PutStream(context.Background())
	//
	//i := 0
	//for {
	//	i++
	//	err := stream.Send(&proto.StreamReq{Data: "客户端流模式111"})
	//	fmt.Println(err)
	//	if errors.Is(err, io.EOF) {
	//		break
	//	}
	//	time.Sleep(time.Second)
	//	if i > 10 {
	//		break
	//	}
	//}
	//双向流
	allStream, err := client.AllStream(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		for {
			recv, err := allStream.Recv()
			if err == io.EOF {
				fmt.Println("client recv EOF")
				break
			}
			if err != nil {
				fmt.Println("client recv err:", err)
				break
			}
			fmt.Println("收到服务端消息:", recv.Data)
		}
	}()
	go func() {
		defer wg.Done()
		for i := 0; i < 10; i++ { // 限制发送次数，避免无限循环
			err := allStream.SendMsg(&proto.StreamReq{Data: fmt.Sprintf("我是客户端，这是第%d条消息", i)})
			if err == io.EOF {
				fmt.Println("client send EOF")
				return
			}
			if err != nil {
				fmt.Println("client send msg :", err)
				return
			}
			fmt.Println("客户端发送消息成功")
			time.Sleep(time.Second)
		}
	}()
	wg.Wait()
	fmt.Println("client done")
}
